package com.aloda.controller.common;

import com.aloda.constant.MessageConstant;
import com.aloda.exception.UploadErrorException;
import com.aloda.result.Result;
import com.aloda.utils.FileUploadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@ConditionalOnProperty(prefix = "supermarket.LocalFileController", name = "enable", matchIfMissing = false)
@Slf4j
public class LocalFileController {

    @Autowired
    private FileUploadUtil fileUploadUtil;

    /**
     * 管理端文件上传
     * @param file
     * @return
     */
    @PostMapping("/admin/common/upload")
    public Result<String> upload(MultipartFile file){
        log.info("文件上传：{}",file);
        String url;
        try {
            url = fileUploadUtil.saveFile(file);
            log.info("上传地址{}",url);
            return Result.success(url);
        } catch (IOException e) {
            throw new UploadErrorException(MessageConstant.UPLOAD_ABNORMAL);
        }
    }


    /**
     * 用户端图片上传
     * @param file
     * @return
     */
    @PostMapping("/user/common/upload")
    public Result<String> UserUpload(MultipartFile file){
        log.info("用户端上传{}",file);
        String url;
        try {
            url = fileUploadUtil.saveFile(file);
            log.info("图片上传地址{}",url);
            return Result.success(url);
        } catch (IOException e) {
            throw new UploadErrorException(MessageConstant.UPLOAD_ABNORMAL);
        }
    }
}
